import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class AddAnniversaryPage extends StatefulWidget {
  const AddAnniversaryPage({super.key});

  @override
  State<AddAnniversaryPage> createState() => _AddAnniversaryPageState();
}

class _AddAnniversaryPageState extends State<AddAnniversaryPage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _noteController = TextEditingController();
  final TextEditingController _customTypeController = TextEditingController();
  DateTime _selectedDate = DateTime.now();
  bool _isRepeat = true;
  String? _selectedType; // 标签内容，emoji+文字
  Color _selectedColor = const Color(0xFFFF6B35);

  // 常用标签
  final List<String> _defaultTags = [
    '🎂生日',
    '💍结婚',
    '❤️恋爱',
    '🎓毕业',
    '💼工作',
  ];
  // 历史自定义标签
  List<String> _customTags = [];

  // 弹窗输入自定义标签
  void _showCustomTagDialog() async {
    _customTypeController.clear();
    String? result = await showDialog<String>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('自定义标签'),
          content: TextField(
            controller: _customTypeController,
            autofocus: true,
            decoration: const InputDecoration(
              hintText: '如：🎉纪念日',
            ),
            maxLength: 10,
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                String value = _customTypeController.text.trim();
                if (value.isNotEmpty) {
                  Navigator.of(context).pop(value);
                }
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
    if (result != null && result.isNotEmpty) {
      setState(() {
        if (!_customTags.contains(result)) {
          _customTags.add(result);
        }
        _selectedType = result;
      });
    }
  }

  final List<Color> _colorOptions = [
    Color(0xFFFF6B35),
    Color(0xFFFF8E9E),
    Color(0xFF4A90E2),
    Color(0xFF7ED957),
    Color(0xFFB47AEA),
  ];

  @override
  Widget build(BuildContext context) {
    List<String> allTags = [..._defaultTags, ..._customTags];
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加纪念日'),
        backgroundColor: Colors.white,
        foregroundColor: Color(0xFF333333),
        elevation: 1,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: '纪念日名称',
                  border: OutlineInputBorder(),
                ),
                validator: (v) => v == null || v.isEmpty ? '请输入名称' : null,
              ),
              const SizedBox(height: 16),
              Text('类型', style: TextStyle(fontWeight: FontWeight.bold)),
              const SizedBox(height: 8),
              // 优化：标签区和自定义按钮分离，标签横向滚动，自定义按钮固定在右侧
              Row(
                children: [
                  // 标签横向滚动
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        children: List.generate(allTags.length, (idx) {
                          final tag = allTags[idx];
                          final selected = _selectedType == tag;
                          return Padding(
                            padding: const EdgeInsets.only(right: 12),
                            child: ChoiceChip(
                              label: Text(tag, style: TextStyle(color: selected ? Colors.white : Color(0xFF333333))),
                              selected: selected,
                              selectedColor: _selectedColor,
                              onSelected: (_) {
                                setState(() => _selectedType = tag);
                              },
                              backgroundColor: Colors.grey[200],
                            ),
                          );
                        }),
                      ),
                    ),
                  ),
                  // 固定“+自定义”按钮
                  Padding(
                    padding: const EdgeInsets.only(left: 4),
                    child: ActionChip(
                      label: Row(
                        children: const [
                          Icon(Icons.add, size: 18, color: Color(0xFF4A90E2)),
                          SizedBox(width: 2),
                          Text('自定义', style: TextStyle(color: Color(0xFF4A90E2))),
                        ],
                      ),
                      backgroundColor: Colors.grey[100],
                      onPressed: _showCustomTagDialog,
                    ),
                  ),
                ],
              ),
              if (_selectedType == null) ...[
                const SizedBox(height: 8),
                const Text('请选择或自定义一个标签', style: TextStyle(color: Colors.red, fontSize: 12)),
              ],
              const SizedBox(height: 16),
              Text('日期', style: TextStyle(fontWeight: FontWeight.bold)),
              const SizedBox(height: 8),
              InkWell(
                onTap: () async {
                  final picked = await showDatePicker(
                    context: context,
                    initialDate: _selectedDate,
                    firstDate: DateTime(1900),
                    lastDate: DateTime(2100),
                  );
                  if (picked != null) {
                    setState(() => _selectedDate = picked);
                  }
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 12),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey[300]!),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.calendar_today, size: 18, color: Color(0xFFFF6B35)),
                      const SizedBox(width: 8),
                      Text(DateFormat('yyyy-MM-dd').format(_selectedDate)),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _noteController,
                decoration: const InputDecoration(
                  labelText: '备注',
                  border: OutlineInputBorder(),
                ),
                maxLines: 2,
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  const Text('年度重复'),
                  Switch(
                    value: _isRepeat,
                    onChanged: (v) => setState(() => _isRepeat = v),
                    activeColor: _selectedColor,
                  ),
                ],
              ),
              const SizedBox(height: 16),
              Text('主题颜色', style: TextStyle(fontWeight: FontWeight.bold)),
              const SizedBox(height: 8),
              Row(
                children: _colorOptions.map((c) => GestureDetector(
                  onTap: () => setState(() => _selectedColor = c),
                  child: Container(
                    margin: const EdgeInsets.only(right: 12),
                    width: 28,
                    height: 28,
                    decoration: BoxDecoration(
                      color: c,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: _selectedColor == c ? Colors.black : Colors.transparent,
                        width: 2,
                      ),
                    ),
                  ),
                )).toList(),
              ),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _selectedColor,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                  ),
                  onPressed: () {
                    if ((_formKey.currentState?.validate() ?? false) && _selectedType != null) {
                      // TODO: 保存逻辑
                      Navigator.of(context).pop();
                    }
                  },
                  child: const Text('保存', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
} 